from django.shortcuts import render, HttpResponse
from AirWeb.models import AirData, Warn
from django.db.models import Count, Min, Max
import json


# Create your views here.

def fanAirWebData(request):
    dist = {
        "air": []
    }

    year = request.GET.get("year")
    city = request.GET.get("city")
    data = AirData.objects.all().filter(date__year=year, city=city).order_by("date")
    for da in data:
        d = {
            "pm10": da.pm10,
            "pm25": da.pm25,
            "co": da.co,
            "no2": da.no2,
            "so2": da.so2,
            "o3": da.o3,
            "date": da.date.strftime("%Y-%m-%d"),
            "aqi": da.aqi,
        }
        dist["air"].append(d)

    response = HttpResponse(json.dumps(dist))

    return response


def GetYears(request):
    dist = {
        "years": []
    }
    data = AirData.objects.filter(status=1)
    for da in data.values():
        item = da["date"].year
        if item not in dist["years"]:
            dist["years"].append(item)

    return HttpResponse(json.dumps(dist))


def GetCity(request):
    dist = {
        "citys": []
    }
    data = AirData.objects.filter(status=1)
    for da in data.values():
        item = da["city"]
        if item not in dist["citys"]:
            dist["citys"].append(item)

    resp = HttpResponse(json.dumps(dist))
    resp['Access-Control-Allow-Origin'] = '*'
    if request.method == 'OPTIONS':
        # 所有的头信息都允许
        resp['Access-Control-Allow-Headers'] = '*'

    return resp


def GetWarn(request):
    item = Warn.objects.all().values("city").annotate(c=Count('city')).order_by('-c')[:5]
    dist = {
        "warn": [],
    }

    for it in item:
        da = {"city": it["city"],
              "count": it['c']}

        dist["warn"].append(da)

    return HttpResponse(json.dumps(dist))


def index(request):
    return render(request, "index.html")
